package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author mengwei
 * @date 2019/8/9
 * @desc
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    RoleDao roleDao;

    @Autowired
    PermissionDao permissionDao;

    /**
     * 获取当前用户信息
     * 通过用户Id获取所有角色信息
     * 通过角色Id获取所有权限信息
     * @param username
     * @return
     */
    @Override
    public SysUser findUserByUsername(String username) {
        //根据用户名获取用户信息
        SysUser sysUser = userDao.findUserByUsername(username);
        if (sysUser == null){
            return null;
        }
        //根据用户Id获取所有角色信息
        Set<Role> roles = roleDao.findRolesByUserId(sysUser.getId());
        if (roles == null || roles.size() == 0){
            return sysUser;
        }
        for (Role role : roles) {
            //根据角色Id获取所有权限信息
            Set<Permission> permissions = permissionDao.findPermissionsByRoleId(role.getId());
            role.setPermissions(permissions);
        }

        //组合数据
        sysUser.setRoles(roles);
        return sysUser;
    }
}
